﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using CB.Logic;
using Swift.Lib;
using ColorBlock = CB.Logic.ColorBlock;
using Swift;
using System;

namespace CB.Client
{
    public class UIColorGame : UIGame<ColorGame, ColorBlock, ColorBlockIcon>
    {
        private void Awake()
        {
            base.Awake();

            var tbs = TargetBlocksTrans.GetComponentsInChildren<ColorBlockIcon>();
            int index = 0;
            for (int i = 0; i < 3; i++)
            {
                var l = new List<ColorBlockIcon>();
                for (int j = 0; j < 3; j++)
                {
                    l.Add(tbs[index]);
                    index++;
                }
                TargetBlockIcons.Add(l);
            }
        }

        private void Start()
        {
            FC.For2(gameData.Height, gameData.Width, (x, y) =>
            {
                var block = BlockIcons[y][x];
                block.InitMaterial();
            });

            FC.For2(gameData.Height - 2, gameData.Width - 2, (x, y) =>
            {
                var block = TargetBlockIcons[y][x];
                block.InitMaterial();
            });
        }

        public override ColorGame GameData
        {
            get => gameData;
            protected set
            {
                if (value == null) return;

                gameData = value;

                for (int i = 0; i < gameData.Height; i++)
                {
                    for (int j = 0; j < gameData.Width; j++)
                    {
                        BlockIcons[i][j].SetData(gameData.Blocks[i][j]);
                    }
                }

                for (int i = 0; i < gameData.Height - 2; i++)
                {
                    for (int j = 0; j < gameData.Width - 2; j++)
                    {
                        TargetBlockIcons[i][j].SetData(gameData.TargetBlocks[i][j]);
                    }
                }
            }
        }
        private ColorGame gameData;

        public override void SetData()
        {
            GameData = Player.Instance.GameData as ColorGame;
        }

        public override IEnumerator Dissolve(Action act)
        {
            OnAni = true;
            FC.For2(gameData.Height, gameData.Width, (x, y) =>
            {
                var block = BlockIcons[y][x];
                block.StartDissolve(DissolveTime / 2);
            });

            FC.For2(gameData.Height - 2, gameData.Width - 2, (x, y) =>
            {
                var block = TargetBlockIcons[y][x];
                block.StartDissolve(DissolveTime / 2);
            });

            yield return new WaitForSeconds(DissolveTime / 2);
            act?.Invoke();
            yield return new WaitForSeconds(DissolveTime / 2);

            OnAni = false;
        }
    }
}
